/**
 * Session Monitor task, alerts the user that their session will expire in 60 seconds and provides
 * the options to continue working or logout.  If the count-down timer expires,  the user is automatically
 * logged out.
 */
Ext.define('DragonApp.ux.session.SessionMonitor', {
    singleton: true,

    requires: [
        'DragonApp.util.Msg'
    ],

    remaining: 0,
    lastActive: null,
    interval: 1000 * 10, // run every 10 seconds.
    maxInactive: 1000 * 60 * 15, // 15 minutes of inactivity allowed; set it to 1 for testing.

    ui: Ext.getBody(),

    /**
     * Dialog to display expiration message and count-down timer.
     */
    window: Ext.create('Ext.window.Window', {
        bodyPadding: 5,
        closable: false,
        closeAction: 'hide',
        modal: true,
        resizable: false,
        title: '登录超时提示',
        width: 325,
        items: [{
            xtype: 'container',
            frame: true,
            html: ''
        }, {
            xtype: 'label',
            text: ''
        }],
        buttons: [{
            text: '保持登录',
            handler: function() {

                Ext.TaskManager.stop(DragonApp.ux.session.SessionMonitor.countDownTask);
                DragonApp.ux.session.SessionMonitor.window.hide();
                DragonApp.ux.session.SessionMonitor.start();

                Ext.data.JsonP.request({

                    url: DragonApp.ux.config.Config.getUrl('/index/Account/keepSessionAlive/'),
                    callbackKey: "callback",
                    async: false,

                    success: function(result) {
                        switch (result.success) {
                            case true:
                                console.log(result.msg);
                                break;
                            case false:

                                //重新开始计时
                                DragonApp.util.Msg.showErrorMsg(result.msg);
                                console.log('keepSessionAlive success failure');

                                Ext.TaskManager.stop(DragonApp.ux.session.SessionMonitor.sessionTask);
                                Ext.TaskManager.start(DragonApp.ux.session.SessionMonitor.sessionTask);
                                break;
                        }
                    },
                    failure: function(result) {

                        //重新开始计时
                        DragonApp.util.Msg.showErrorMsg(result);
                        console.log('keepSessionAlive failure');

                        Ext.TaskManager.stop(DragonApp.ux.session.SessionMonitor.sessionTask);
                        Ext.TaskManager.start(DragonApp.ux.session.SessionMonitor.sessionTask);
                    }
                });
            }
        }, {
            text: '登出',
            action: 'logout',
            handler: function() {
                Ext.TaskManager.stop(DragonApp.ux.session.SessionMonitor.countDownTask);
                DragonApp.ux.session.SessionMonitor.window.hide();

                // find and invoke your app's "Logout" button.
                var btn = Ext.ComponentQuery.query('button#logout')[0];
                btn.fireEvent('click', btn);
            }
        }]
    }),


    /**
     * Sets up a timer task to monitor for mousemove/keydown events and
     * a count-down timer task to be used by the 60 second count-down dialog.
     */
    constructor: function(config) {
        var me = this;

        // session monitor task
        this.sessionTask = {
            run: me.monitorUI,
            interval: me.interval,
            scope: me
        };

        // session timeout task, displays a 60 second countdown
        // message alerting user that their session is about to expire.
        this.countDownTask = {
            run: me.countDown,
            interval: 1000,
            scope: me
        };
    },


    /**
     * Simple method to register with the mousemove and keydown events.
     */
    captureActivity: function(eventObj, el, eventOptions) {
        this.lastActive = new Date();
    },


    /**
     *  Monitors the UI to determine if you've exceeded the inactivity threshold.
     */
    monitorUI: function() {
        var now = new Date();
        var inactive = (now - this.lastActive);

        if (inactive >= this.maxInactive) {
            this.stop();

            this.window.show();
            this.remaining = 60; // seconds remaining.
            Ext.TaskManager.start(this.countDownTask);
        }
    },


    /**
     * Starts the session timer task and registers mouse/keyboard activity event monitors.
     */
    start: function() {
        this.lastActive = new Date();
        this.ui = Ext.getBody();

        this.ui.on('mousemove', this.captureActivity, this);
        this.ui.on('keydown', this.captureActivity, this);

        Ext.TaskManager.start(this.sessionTask);
    },

    /**
     * Stops the session timer task and unregisters the mouse/keyboard activity event monitors.
     */
    stop: function() {
        Ext.TaskManager.stop(this.sessionTask);
        this.ui.un('mousemove', this.captureActivity, this); //  always wipe-up after yourself...
        this.ui.un('keydown', this.captureActivity, this);
    },


    /**
     * Countdown function updates the message label in the user dialog which displays
     * the seconds remaining prior to session expiration.  If the counter expires, you're logged out.
     */
    countDown: function() {
        //this.window.down('label').update('Your session will expire in ' +  this.remaining + ' second' + ((this.remaining == 1) ? '.' : 's.') );
        this.window.down('label').update('您将在 ' + this.remaining + ' 秒内登出系统');
        --this.remaining;

        if (this.remaining < 0) {
            var btn = Ext.ComponentQuery.query('button#logout')[0];
            btn.fireEvent('click', btn);
        }
    }
});